/*
 * Android Runner is a multiplayer GPS game fully written by Xurxo Mendez Perez
 * 
 * Copyright (C) 2009 Xurxo Mendez Perez
 *   
 * This file is part of Android Runner.
 * 
 * Android Runner is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Android Runner is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Android Runner.  If not, see <http://www.gnu.org/licenses/>.
 */

package es.sonxurxo.gpsgame.client.cv.activity;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import es.sonxurxo.gpsgame.client.R;
import es.sonxurxo.gpsgame.client.cv.common.actions.CommonActions;
import es.sonxurxo.gpsgame.client.cv.common.dialogs.CommonDialogs;
import es.sonxurxo.gpsgame.client.model.service.player.HttpPlayerServiceImpl;
import es.sonxurxo.gpsgame.client.model.service.to.Player;
import es.sonxurxo.gpsgame.client.util.exception.ServerException;

/**
 * 
 * @author "Xurxo Mendez Perez"
 *
 */
public class ChangePasswordActivity extends Activity {
	
	private static final int LOGOUT_ID = Menu.FIRST;
	
	private Player player;
	
	private TextView loginView, oldPasswordView, newPasswordView, 
	confirmNewPasswordView;
	private Button changeButton;
	
	private ChangePasswordTask changePasswordTask;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.change_password_page);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_1);
        
    	changeButton = (Button)findViewById(R.id.cp_b_change);
        loginView = (TextView)findViewById(R.id.cp_tv_login);
        player = (Player)getIntent().getExtras().getSerializable("player");
        ((TextView)findViewById(R.id.title_right_text)).setText(player.getLogin());
        
        loginView.setText(player.getLogin());
        oldPasswordView = (EditText)findViewById(R.id.cp_et_old_password);
        newPasswordView = (EditText)findViewById(R.id.cp_et_new_password);
        confirmNewPasswordView = (EditText)findViewById(R.id.cp_et_confirm_new_password);
        
        changeButton.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
    			doChangePassword();
    		}	
        });
	}
	
	private void showToast(int messageId) {
		Toast.makeText(this, messageId,
                Toast.LENGTH_SHORT).show();
	}	
	
	private void doChangePassword() {

		String oldPassword = oldPasswordView.getText().toString();
		String newPassword = newPasswordView.getText().toString();
		String confirmNewPassword = confirmNewPasswordView.
			getText().toString();
		
		if (oldPassword.equals("") || 
				newPassword.equals("") || confirmNewPassword.equals("")) {
			showToast(R.string.rp_wrong_fields);
			return;
		}
		else if ((!newPassword.equals("") && 
				!confirmNewPassword.equals("")) && !newPassword.equals(confirmNewPassword)){
			showToast(R.string.rp_different_passwords);
			return;
		}
		
		changePasswordTask = new ChangePasswordTask(oldPassword, newPassword);
		Thread loginThread = new Thread(null, changePasswordTask, "ChangePassword");
		loginThread.start();
		showDialog(CommonDialogs.CONNECTING_TO_SERVER_DIALOG_ID);
		
//		try {
//
//			HttpHelper.getInstance().changePassword(oldPassword, newPassword);
//
//			setResult(RESULT_OK);
//        	finish();
//			
//		} catch (ServerException e) {
//			errorMessage = e.getLocalizedMessage();
//			switch (e.getCode()) {
//			case ServerException.DUPLICATE_INSTANCE_CODE:
//	    		showDialog(CommonDialogs.SERVER_ERROR_DIALOG_ID);
//	    		break;
//	    	case ServerException.INCORRECT_PASSWORD_CODE:
//	    		showToast(R.string.error_incorrect_password_message);
//	    		break;
//	    	case ServerException.SERVER_OFFLINE_CODE:
//        		showDialog(CommonDialogs.SERVER_OFFLINE_DIALOG_ID);
//        		break;
//	    	case ServerException.INSTANCE_NOT_FOUND_CODE:
//	    		showDialog(CommonDialogs.SERVER_ERROR_DIALOG_ID);
//	    		break;
//	    	case ServerException.EXCEPTION_CODE:
//	    		showDialog(CommonDialogs.SERVER_ERROR_DIALOG_ID);
//	    		break;
//	    	}
//			return;
//		} catch (Exception e) {
//			errorMessage = e.getLocalizedMessage();
//			showDialog(CommonDialogs.CLIENT_ERROR_DIALOG_ID);
//			return;
//		}
	}
	
	private void doLogout() {
		CommonActions.launchLogoutThread(player.getLogin(), this);
	}
	
	@Override
    protected Dialog onCreateDialog(int id) {
    	return CommonDialogs.createDialog(id, this);
    }
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, LOGOUT_ID,0, R.string.fg_mo_logout);
        return true;
    }
    
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
        case LOGOUT_ID:
        	doLogout();
        	break;
        }
        
        return super.onMenuItemSelected(featureId, item);
    }

	private class LoginHandler extends Handler {

		public LoginHandler(Looper looper) {
			super(looper);
		}
		
		@Override
		public void handleMessage(Message msg) {
			dismissDialog(CommonDialogs.CONNECTING_TO_SERVER_DIALOG_ID);
			ServerException sE = 
				(ServerException)msg.getData().getSerializable("ServerException");
			if (sE	!= null) {
	        	CommonDialogs.errorMessage = sE.getMessage();
	        	switch (sE.getCode()) {
				case ServerException.DUPLICATE_INSTANCE_CODE:
		    		showDialog(CommonDialogs.SERVER_ERROR_DIALOG_ID);
		    		break;
		    	case ServerException.INCORRECT_PASSWORD_CODE:
		    		showToast(R.string.error_incorrect_password_message);
		    		break;
		    	case ServerException.SERVER_OFFLINE_CODE:
	        		showDialog(CommonDialogs.SERVER_OFFLINE_DIALOG_ID);
	        		break;
		    	case ServerException.INSTANCE_NOT_FOUND_CODE:
		    		showDialog(CommonDialogs.CONNECTION_LOST_DIALOG_ID);
		    		break;
		    	case ServerException.EXCEPTION_CODE:
		    		showDialog(CommonDialogs.SERVER_ERROR_DIALOG_ID);
		    		break;
		    	}
	        	return;
	        }
        	Exception e = 
	        	(Exception)msg.getData().getSerializable("Exception");
	        	if (e != null) {
	        		CommonDialogs.errorMessage = e.getLocalizedMessage();
		        	showDialog(CommonDialogs.CLIENT_ERROR_DIALOG_ID);
		        	return;
	        	}
	        if (msg.getData().getBoolean("result")) {
	        	setResult(RESULT_OK);
	        	finish();
	        }
		}
	}
	
	private class ChangePasswordTask implements Runnable {

		String newPassword, oldPassword;
		HttpPlayerServiceImpl playerService;
		
		ChangePasswordTask(String login, String newPassword) {
			this.newPassword = login;
			this.oldPassword = newPassword;
			playerService = new HttpPlayerServiceImpl();
		}
		
		public void run() {
			
			LoginHandler handler = new LoginHandler(Looper.getMainLooper());
			Bundle data = new Bundle();
			Message msg = new Message();
			try {
				
				boolean result = playerService.changePassword(
						newPassword, oldPassword);
				data.putSerializable("result", result);
				msg.setData(data);
				handler.sendMessage(msg);
				
			} catch (ServerException e) {
	        	data.putSerializable("ServerException", e);
	        	msg.setData(data);
				handler.sendMessage(msg);
	        } catch (Exception e) {
	        	data.putSerializable("Exception", e);
	        	msg.setData(data);
				handler.sendMessage(msg);
	        }
		}
	}
}
